<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
/**
 * 门店管理
 * @package app\cms\admin
 */
class Storelogic{

	/**
     * 门店列表
     * @param  int $user_id  操作用户ID
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function store_index($user_id,$title, $lat = '', $lon= ''){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'title'   	=> $title,
				'lat'   	=> $lat,
				'lon'   	=> $lon,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $map = [];//搜索处理
            if($title != '') $map[] = ['title', 'like', '%'. $title .'%'];
            $map[] = ['id', '=', 9];
			// $list =  model('ErpStore', 'model') -> where($map) -> order('sort asc, create_time desc')->paginate();//获取列表
			$list =  model('ErpStore', 'model') -> where($map) -> order('sort asc, create_time desc')->select();//获取列表
			$rel_list = [];
            foreach($list as $key => $value){
				$rel_list[$key]['id'] 			= (int)$value['id'];
				$rel_list[$key]['title'] 		= (string)$value['title'];
				$rel_list[$key]['mobile'] 		= (int)$value['mobile'];
				$rel_list[$key]['address'] 		= (string)$value['address'];
				$rel_list[$key]['sort'] 		= (int)$value['sort'];
				$rel_list[$key]['code'] 		= (string)$value['code'];
				$rel_list[$key]['createTime'] 	= (string)$value['create_time'];
                $rel_list[$key]['lon'] 	        = (string)$value['lon'];
                $rel_list[$key]['lat'] 	        = (string)$value['lat'];
//关联仓库
                $data_warehouse_list = model('ErpStoreWarehouse', 'model') -> getStoreWarehouse($value['id']);
                $data_warehouse = [];
                if(!empty($data_warehouse_list['data'])){
                    $data_warehouse_type = ['0'=>'暂无','1'=>'分仓','2'=>'总仓'];
                    foreach ($data_warehouse_list['data'] as $k_dw => $v_dw){
                        $data_warehouse[$k_dw]['id']            = (int)$v_dw['id'];
                        $data_warehouse[$k_dw]['title']         = (string)$v_dw['title'];
                        $data_warehouse[$k_dw]['address']       = (string)$v_dw['address'];
                        $data_warehouse[$k_dw]['sort']          = (int)$v_dw['sort'];
                        if($v_dw['type'] == '1'){
                            $v_dw['type'] = '分仓';
                        } elseif($v_dw['type'] == '2'){
                            $v_dw['type'] = '总仓';
                        }
                        $data_warehouse[$k_dw]['type']          = (string)$v_dw['type'];
                        $data_warehouse[$k_dw]['warehouseId']   = (int)$v_dw['warehouse_id'];
                        $data_warehouse[$k_dw]['createTime']    = (string)$v_dw['create_time'];
                        $data_warehouse[$k_dw]['updateTime']    = (string)$v_dw['update_time'];
                    }
                }
                if($data_warehouse != '') $rel_list[$key]['dataWarehouse'] = $data_warehouse;
                //关联人员
                $data_storeuser_list = model('ErpStoreUser', 'model') -> where('store_id','=',$value['id']) -> order('create_time desc') -> select();
                $data_store_user = [];
                if( !empty($data_storeuser_list)){
                    foreach ($data_storeuser_list as $k_du => $v_du){
                        $data_store_user[$k_du]['id']           = (int)$v_du['id'];
                        $data_store_user[$k_du]['userName']     = (string)$v_du['user_name'];
                        $data_store_user[$k_du]['nickName']     = (string)$v_du['nick_name'];
                        $data_store_user[$k_du]['password']     = (string)$v_du['password'];
                        $data_store_user[$k_du]['createTime']   = (string)$v_du['create_time'];
                        $data_store_user[$k_du]['updateTime']   = (string)$v_du['update_time'];
                    }
                }
                if($data_store_user != '')  $rel_list[$key]['dataStoreUser'] = $data_store_user;
				//经纬度
				$distance = -1;
				if($lon > 0 && $lat > 0){
					$distance = getdistance($value['lon'], $value['lat'], $lon, $lat);
				}
				$rel_list[$key]['distance'] 	= (int)$distance;
			}
			
			$distance = array_column($rel_list, 'distance');
			array_multisort($distance, SORT_ASC, $rel_list);
            // $result_list = [];
            // $result_list['total']  			= (int)$list -> total();//总数
            // $result_list['current_page']	= (int)$list -> currentPage();//页码
            // $result_list['last_page']   	= (int)$list -> lastPage();//总页数
            // $result_list['per_page']   		= (int)$list -> listRows();//每页条数
            // $result_list['data'] 			= $rel_list;

            $page       = input('page');
            $page_size  = input('page_size');

            $count = count($rel_list);//总条数
            $start=($page-1)*$page_size;//偏移量，当前页-1乘以每页显示条数
            $result_list = array_slice($rel_list, $start, $page_size);
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 添加数据
     * @param title 	        string 店铺名称
     * @param address 	        string 地址
     * @param sort 		        int    排序
     * @param code 		        string 门店编码
     * @param warehouse_id_zf 	array 仓库id
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function add($user_id, $title,$address, $sort, $code, $warehouse_id_zf, $lat, $lon, $mobile){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'title' 	=> $title,
				'address' 	=> $address,
				'sort' 		=> $sort,
				'code' 		=> $code,
				'lat' 		=> $lat,
				'lon' 		=> $lon,
				'mobile' 	=> $mobile,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$rel = model('ErpStore') -> addData($title,$address, $sort, $code, $lat, $lon, $mobile);//添加
            //$rel = array('code'=>200,'message'=>'success','data'=>'28');
            //同时插入并关联仓库id
            if($rel['code'] == 200 && isset($rel['data'])){
                $storeId = $rel['data'];
                if($storeId){
                    $s_w = [];
                    //如果不是数组就拆分
                    if(!is_array($warehouse_id_zf)){
                        $warehouse_id = explode(',',$warehouse_id_zf);
                    }else{
                        $warehouse_id = $warehouse_id_zf;
                    }
                    foreach($warehouse_id as $key => $value) {
                        $s_w[$key]['warehouse_id'] = $value;
                        $s_w[$key]['store_id']     = $storeId;
                        $s_w[$key]['create_time']  = time();
                        $s_w[$key]['update_time']  = time();
                    }
                    //循环插入数据
                    $rel = model('ErpStoreWarehouse','model') -> addDataAll($s_w);
                    if($rel['code'] < 0){
                        DB::rollback();
                        return array_out(-1005, 'error2');//门店仓库表关联更新失败 返回-1005,error
                    }
                }
            }else{
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success',$rel['data']);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 编辑数据
     * @param id 		int id
     * @param title 	string 店铺名称
     * @param address 	string 地址
     * @param sort 		int    排序
     * @param code 		string 门店编码
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function edit($user_id,$id, $title, $address, $sort, $code, $lat, $lon, $mobile){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
                'title' 	=> $title,
                'address' 	=> $address,
				'sort' 		=> $sort,
				'code' 		=> $code,
				'lat' 		=> $lat,
				'lon' 		=> $lon,
				'mobile' 	=> $mobile,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			
			$rel = model('ErpStore') -> editData($id ,$title, $address, $sort, $code, $lat, $lon, $mobile);
            if($rel['code'] == 200){
            }else{
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
     * 删除
     * @param  int    $user_id   操作用户ID
     * @param  int    $id  		门店id
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function delete($user_id, $id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            // 获取关联仓库id
			$s_w_ids = model('ErpStoreWarehouse') -> where('store_id',$id)->field('id')->select()->toArray();
			// 删除的门店id&关联仓库id
			$rel = model('ErpStore') -> deleteData($id);
			if($rel['code'] == 200 && !empty($s_w_ids)){
                $s_w_ids = array_column($s_w_ids,'id');
                $rel = model('ErpStoreWarehouse') -> deleteData($s_w_ids);
            }
			if($rel['code'] < 0){
				return array_out(-1005, 'error');//删除失败 返回-1005,error
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	/**
     * 更新门店价格
     * @param  int    $user_id   操作用户ID
     * @param  int    $store_id  门店id
     * @param  int    $sku_id    sku_id
     * @param  string $price	 价格
     * @author shiqiang
     * @return array_out(code, message, data)
     */
    public function update_sku_price($user_id, $store_id, $sku_id, $price, $sku_status){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'store_id' 	=> $store_id,
				'sku_id' 	=> $sku_id,
				'price' 	=> $price,
				'sku_status' 	=> $sku_status,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            // 获取关联仓库id
			$warehouse_list = model('ErpStoreWarehouse') -> where('store_id',$store_id) -> column('warehouse_id');
			if(!empty($warehouse_list)){
				foreach($warehouse_list as $warehouse_id){
                    //根据仓库id 查询一下是否属于分仓（只更新对应分仓id）
                    $rel = model('ErpWarehouse') -> find($warehouse_id);
                    if(isset($rel->type) && $rel->type != 1){
                        continue;
                    }
					$map = [];
					$map['warehouse_id'] 	= $warehouse_id;
					$map['sku_id'] 			= $sku_id;

					$stock = model('ErpGoodsWarehouseStockNum') -> where($map) -> find();//sku是否存在

					if(!empty($stock)){
						$data = [];
						$data['price'] 		= $price;
						$data['sku_status']	= $sku_status;
						
						//更新价格
						$res = model('ErpGoodsWarehouseStockNum') -> update($data, $map);
						if(!$res){
							return array_out(-1005, 'error1');
						}
					}else{
						$goods_id = model('ErpGoodsSku') -> find($sku_id) -> goods_id;
						//新建库存
						$res = model('ErpGoodsWarehouseStockNum') -> addData($warehouse_id, $sku_id, 0, 0, $goods_id, $price);
						if($res['code'] < 0){
							return array_out(-1005, 'error2');
						}
					}
				}
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
}